const mysql = require('mysql2/promise')
const bcrypt = require('bcrypt')

const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'GKL9512357',
  database: 'novel_platform',
  charset: 'utf8mb4'
}

async function createTestUser () {
  let connection
  try {
    connection = await mysql.createConnection(dbConfig)

    const testEmail = 'test@example.com'
    const testPassword = '123456'
    const testUsername = 'testuser'
    const testNickname = '测试用户'

    console.log('🔍 检查用户是否已存在...')

    // 检查用户是否已存在
    const [existingUsers] = await connection.execute(
      'SELECT id FROM users WHERE email = ? OR username = ?',
      [testEmail, testUsername]
    )

    if (existingUsers.length > 0) {
      console.log('⚠️ 用户已存在，删除后重新创建...')
      await connection.execute(
        'DELETE FROM users WHERE email = ? OR username = ?',
        [testEmail, testUsername]
      )
    }

    console.log('🔐 加密密码...')
    const saltRounds = 10
    const passwordHash = await bcrypt.hash(testPassword, saltRounds)

    console.log('👤 创建测试用户...')
    const [result] = await connection.execute(
      `INSERT INTO users (username, email, nickname, password_hash, role, status, level, coins, is_vip, created_at, updated_at) 
       VALUES (?, ?, ?, ?, 'user', 'active', 1, 100, false, NOW(), NOW())`,
      [testUsername, testEmail, testNickname, passwordHash]
    )

    console.log('✅ 测试用户创建成功！')
    console.log(`📧 邮箱: ${testEmail}`)
    console.log(`🔑 密码: ${testPassword}`)
    console.log(`👤 用户名: ${testUsername}`)
    console.log(`🆔 用户ID: ${result.insertId}`)

    // 验证创建的用户
    console.log('\n🔍 验证用户...')
    const [newUser] = await connection.execute(
      'SELECT id, username, email, nickname, password_hash FROM users WHERE id = ?',
      [result.insertId]
    )

    if (newUser.length > 0) {
      console.log('✅ 用户创建验证成功')

      // 测试密码验证
      const isValidPassword = await bcrypt.compare(
        testPassword,
        newUser[0].password_hash
      )
      console.log(`🔐 密码验证: ${isValidPassword ? '成功' : '失败'}`)
    }
  } catch (error) {
    console.error('❌ 错误:', error.message)
  } finally {
    if (connection) await connection.end()
  }
}

createTestUser()
